<template>
	<div  class="wrapper">
		<div  style="position: relative;">
		<i class="el-icon-close" @click="closeDialogTop()" style="position:absolute;cursor: pointer; font-size:22px; top: -48px; right: 0px"></i>
    </div>
		<!-- <Anchor class="mainAnchor" :labelList="labels" activeId="row-01" labelWidth="80">
			<div class="line" id="row-01" style="min-height:780px"> -->
<!--    服务中心基本信息-->
				<BreakSpace :label="labels[0].title" :containerStyle="{ marginBottom: '10px' }" />
				<infoBase ref="infoBase" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoBaseChange"/>
			<!-- </div>
			<div class="line" id="row-01" style="min-height:780px"> -->
<!--    服务战区信息-->
        <BreakSpace :label="labels[1].title" :containerStyle="{ marginBottom: '10px' }" />
        <infoArea ref="infoArea" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoAreaChange"/>
      <!-- </div>
      <div class="line" id="row-01" style="min-height:780px"> -->
<!--    备件采购信息-->
        <BreakSpace :label="labels[2].title" :containerStyle="{ marginBottom: '10px' }" />
        <infoPart ref="infoPart" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoPartChange"/>
      <!-- </div>
      <div class="line" id="row-01" style="min-height:780px"> -->
<!--    注册信息-->
        <BreakSpace :label="labels[3].title" :containerStyle="{ marginBottom: '10px' }" />
        <infoPower ref="infoPower" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoPowerChange"/>
<!--    财务信息-->
        <BreakSpace :label="labels[4].title" :containerStyle="{ marginBottom: '10px' }" />
        <infoFinance ref="infoFinance" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoFinanceChange"/>
      <!-- </div>
      <div class="line" id="row-02"> -->
<!--    关键岗位信息-->
    <!--<BreakSpace :label="labels[5].title" :containerStyle="{ marginBottom: '10px' }" />
    <infoKeyPosition ref="infoKeyPosition" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoKeyPositionChange"/>-->
<!--    授权车型-->
        <BreakSpace :label="labels[5].title" :containerStyle="{ marginBottom: '10px' }" />
        <infoProduct ref="infoProduct" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoProductChange"/>
<!--    授权PDI站点-->
        <BreakSpace :label="labels[6].title" :containerStyle="{ marginBottom: '10px' }" />
        <infoRelationDealer ref="infoRelationDealer" :formType="value.type" :formOptions="value" v-model="formData" @formchange="infoRelationDealeraChange"/>
			<!-- </div> -->
			<!-- <div class="line" id="row-07">
				<infoOpinion ref="infoOpinion" :formType="value.type" v-model="formData" @formchange="infoOpinionChange"/>
			</div> -->
		<!-- </Anchor> -->
		<div class="dialogBottmView">
			<el-button @click="closeDialogTop">关 闭</el-button>
			<el-button @click="determineDialog()"  v-if="value.type!=='show'" type="primary">保 存</el-button>
			<!-- <el-button @click="determineDialog()" v-if="value.type!=='show'" :disabled="this.formData.status === this.types.DEALER_INFO_STATUS_ENABLE" type="primary">确 定</el-button> -->
<!--			<el-button @click="determineDialog()" v-if="value.type!=='show'" :disabled="okDisabled" type="primary">确 定</el-button>-->
		</div>
	</div>
</template>

<script>
	import { authority } from '@/utils/authMixin';
	import { dictionary } from '@/utils/dictMixin';

	import autoLoding from '@/utils/loding';//等待框
	import infoBase from '../serviceDealerForm/infoBase'; //基本信息
	import infoProduct from '@/pages/cms-pages/origin/originInfo/dealerForm/infoProduct.vue'; //产品授权
	import infoPower from '../serviceDealerForm/infoPower'; //注册信息
	import infoCompany from '../serviceDealerForm/infoCompany'; //公司信息
	import infoStock from '../serviceDealerForm/infoStock'; //股东信息
	import infoFinance from '../serviceDealerForm/infoFinance'; //财务信息
  import infoArea from '../serviceDealerForm/infoArea';//服务展区信息
  import infoPart from '../serviceDealerForm/infoPart';//备件采购信息
  import infoKeyPosition from '../serviceDealerForm/infoKeyPosition';//关键岗位信息
  import infoRelationDealer from '@/pages/cms-pages/origin/originInfo/serviceDealerForm/infoRelationDealer.vue';
	// import infoOpinion from '../serviceDealerForm/infoOpinion'; //审核信息

	import { getDetails } from '@/api/cms-api/origin/originInfo';
	import { addAllData,addAllData4Serv, editAllData,editAllData4Serv, addDetermine, editDetermine } from '@/api/cms-api/origin/originInfo/OEM';
	import * as types from '@/api/cms-api/origin/originInfo/types';
	import { dealerCommon } from '@/api/cms-api/origin/commonDealerType';		//经销商类型工具类
	import { isArray } from 'util';

	import vm from './bridge';

	export default {
		mixins: [authority, dictionary, autoLoding,dealerCommon],
		components: {
			infoBase,infoArea,infoPart,infoKeyPosition,infoProduct,infoPower,infoCompany,infoStock,infoFinance,infoRelationDealer
		},
		props:{
			value: {
				type: Object,
				required: true
			},
		},
		data() {
			return {
				okDisabled:false,
				formData:{},
				labels: [
					{ title: '服务中心基本信息', id: 'row-01' },
          { title: '服务战区信息', id: 'row-02' },
          { title: '备件采购信息', id: 'row-03' },
          { title: '注册信息', id: 'row-04' },
          { title: '财务信息', id: 'row-05' },
/*          { title: '关键岗位信息', id: 'row-06' },*/
          { title: '授权车型', id: 'row-06' },
          { title: '授权PDI站点', id: 'row-07' },
				],
				loadingVm:null,
				types:types
			};
		},
		mounted(){
		  try{
        if(this.value.type != 'add'){
          // this.loadingVm = this.openLoding('.cover-container');
          //按ID获取数据
          this.init();
        }
      }finally{
        // this.closeLoding(this.loadingVm);
      }
		},
		methods: {
			async init(){
			  try{
          let res = await getDetails(this.value.id,{});
          if(res.resultCode === 200){
            //转换附件为list<Sting>
            this.formData = this.transformAllEnclosureString(res.data);
            this.formData.inputNumber = '';
            this.formData.inputChar = '';
            this.$nextTick(() =>{
              this.$refs.infoBase.init();
              this.$refs.infoRelationDealer.init();
              this.$refs.infoPower.init();
              this.$refs.infoArea.init();
              this.$refs.infoPart.init();
              this.$refs.infoFinance.init();
              this.$refs.infoProduct.init();
              this.closeLoding(this.loadingVm);
            });
          }
        }catch(e){
          console.log("页面初始化异常:", e);
        }

			},

			//打开等待遮罩
			openLoding(options){
				let defOptions = {	// 声明一个loading对象
					lock: true, // 是否锁屏
					fullscreen: false,
					body: false,
					target: '.mainAnchor', // 需要遮罩的区域
				};
				defOptions = Object.assign(defOptions,options);
				// this.loadingVm = this.$loading(defOptions);
				return this.$loading(defOptions);
			},
			//关闭等待遮罩
			closeLoding(loading){
				loading.close();
			},

      //保存（不验证）
      async saveDialog(){
			  try{
          this.loadingVm = this.openLoding('.cover-container');
          let allData = this.getSavingData();
          allData.auditStatus = types.DEALER_INFO_STATUS_SAVED;

          if(allData.dealerCompanyId == null || allData.dealerCompanyId == ""){
            if(this.value.type == 'add'){
              this.$notify.warning({title: '提示信息',message:'必须手动选择一个经销商公司'});
              return;

            }
          }

          await this.save(allData);
        }finally {
          this.closeLoding(this.loadingVm);
        }

      },

			//确定（验证并提交）
			async determineDialog() {
			  try{
          this.loadingVm = this.openLoding('.cover-container');
          let allData = this.getSavingData();
          allData.auditStatus = types.DEALER_INFO_STATUS_SAVED;
          // allData.auditStatus = types.DEALER_INFO_STATUS_TO_BE_SUBMITTED;

          if(allData.dealerCompanyId == null || allData.dealerCompanyId == ""){
            if(this.value.type == 'add'){
              this.$notify.warning({title: '提示信息',message:'必须手动选择一个经销商公司'});
              return;

            }
          }
          let f1 = await this.$refs.infoBase.saveDialog();
          let f2 = await this.$refs.infoArea.saveDialog();
          let f3 = await this.$refs.infoPart.saveDialog();
          let f4 = await this.$refs.infoFinance.saveDialog();
          let f5 = await this.$refs.infoProduct.saveDialog();
          let f6 = await this.$refs.infoPower.saveDialog();
          if(!f1 || !f2 || !f3 || !f4 || !f5|| !f6){
            return;
          }
          await this.save(allData);
          // await this.saveDetermine(allData);
        }finally {
          this.closeLoding(this.loadingVm);
        }

			},

      /**
       * 获取待提交数据
       * @returns {*|{}}
       */
      getSavingData(){
        //取数据
        let allData = { ... this.formData};
        allData.shopBusinessType = types.SHOP_BUSINESS_SERVICE;

        //@1
        this.$refs.infoBase.$refs.FormPanel.excuteFormData(this.$refs.infoBase.$refs.FormPanel.form);
        allData = Object.assign(allData,this.$refs.infoBase.$refs.FormPanel.form);
        allData = Object.assign(allData,this.$refs.infoBase.$data.hiddenFormData);

        //关联服务中心信息
        allData.attachRelatedDealerList = this.$refs.infoRelationDealer.saveData.xxList;
        allData.insertAttachRelatedDealerList = this.$refs.infoRelationDealer.$refs.tableInfo.GET_INSERT_ROWS();
        allData.deleteAttachRelatedDealerList = this.$refs.infoRelationDealer.$refs.tableInfo.GET_DELETE_ROWS();

        //注册信息
        this.$refs.infoPower.$refs.FormPanel.excuteFormData(this.$refs.infoPower.$refs.FormPanel.form);
        allData = Object.assign(allData,this.$refs.infoPower.$refs.FormPanel.form);

        //服务战区信息
        this.$refs.infoArea.$refs.FormPanel.excuteFormData(this.$refs.infoArea.$refs.FormPanel.form);
        let serviceAreaInfo = Object.assign({},this.formData.serviceAreaInfo);
        serviceAreaInfo = Object.assign(serviceAreaInfo, this.$refs.infoArea.$refs.FormPanel.form);
        serviceAreaInfo = Object.assign(serviceAreaInfo,this.$refs.infoArea.$data.hiddenFormData);
        allData.serviceAreaInfo = serviceAreaInfo;

        //备件采购信息
        this.$refs.infoPart.$refs.FormPanel.excuteFormData(this.$refs.infoPart.$refs.FormPanel.form);
        allData = Object.assign(allData,this.$refs.infoPart.$refs.FormPanel.form);

        //财务信息
        this.$refs.infoFinance.$refs.FormPanel.excuteFormData(this.$refs.infoFinance.$refs.FormPanel.form);
        allData = Object.assign(allData,this.$refs.infoFinance.$refs.FormPanel.form);

        //授权车型
        this.$refs.infoProduct.$refs.FormPanel.excuteFormData(this.$refs.infoProduct.$refs.FormPanel.form);
        allData = Object.assign(allData,this.$refs.infoProduct.$refs.FormPanel.form);

        //时间转换
        allData.establishmentDate = this.transTiming(allData.establishmentDate);
        allData.offlineDate = this.transTiming(allData.offlineDate);
        allData.effectiveDate = this.transTiming(allData.effectiveDate);
        allData.openDate = this.transTiming(allData.openDate);
        return allData;
      },

      transTiming(value){
        console.log("timing orgin value:",value);
        let regex = /^[1-2][0-9][0-9][0-9]-([1][0-2]|0?[1-9])-([12][0-9]|3[01]|0?[1-9])$/;
        let regex2 = /^[1-2][0-9][0-9][0-9]-([1][0-2]|0?[1-9])-([12][0-9]|3[01]|0?[1-9]) ([01]?[0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$/;
        if (regex.test(value)) {
          value = value + " 00:00:00";
        }else if(regex2.test(value)){
          value = value;
        }else{
          value = value;
        }
        return value;
      },

			//取消操作
			closeDialogTop() {
				this.$confirm('确认关闭窗口吗？您所做的操作将不会被保存！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$emit('close', { visible: false });
				})
			},
			infoBaseChange(data){
				// console.log(2)
				this.$refs.infoBase.saveDialog();
			},
      infoRelationDealeraChange(data){
        this.$refs.infoRelationDealeraChange.saveDialog();
      },
      infoAreaChange(data){
        // console.log(3)
        this.$refs.infoArea.saveDialog();
      },
      infoPartChange(data){
        // console.log(3)
        this.$refs.infoPart.saveDialog();
      },
      infoPowerChange(data){
        // console.log(4)
        this.$refs.infoPower.saveDialog();
      },
			infoProductChange(data){
				// console.log(3)
				this.$refs.infoProduct.saveDialog();
			},
      infoKeyPositionChange(data){
        // console.log(3)
        this.$refs.infoKeyPosition.saveDialog();
      },
			infoFinanceChange(_data){
				// console.log(5)
				this.$refs.infoFinance.saveDialog();
			},
			//判断当前是否需要生成经销商代码
			generateAsNeeded(){
				//不存在经销商代码
				return !this.formData.dealerCode;
			},
			open(data){
				// data.inputNumber = undefined;
				// data.inputChar = '';
				this.$msgbox({
					title:'消息',
					message: <div>
						<el-row class="demo-autocomplete">
							<el-col span={12}>
								<div class="sub-title">数字（1-99）</div>
								<div class="inline-input">
									<div class="el-input el-input--small">
										<input
											type="number"
											autocomplete="off"
											min={1}
											max={99}
											step={1}
											precision={0}
											placeholder="请输入数字（1-99）"
											v-model={data.inputNumber}
											class="el-input__inner"
											onInput={e => {
												// console.log(e.target.value)
												let value = e.target.value;
												let max = e.target.max;
												let min = e.target.min;
												value = String(value).replace(/^\s+|\s+$/g, '');
												let numberValue = Number(value);
												if(isNaN(numberValue)){
													data.inputNumber = min;
													e.target.value = min;
													return;
												}
												if(String(value).indexOf('.') != -1){
													data.inputNumber = min;
													e.target.value = min;
													return;
												}
												if(max){
													if(!(numberValue <= max)){
														data.inputNumber = max;
														e.target.value = max;
														return ;
													}
												}
												if(min){
													if(!(min <= numberValue)){
														data.inputNumber = min;
														e.target.value = min;
														return ;
													}
												}
												data.inputNumber = Number(value);
												e.target.value = Number(value);
											}}
										/>
									</div>
								</div>
							</el-col>
							<el-col span={12}>
								<div class="sub-title">字符（A-Z）</div>
								<div class="inline-input">
									<div class="el-input el-input--small">
										<input
											type="text"
											maxlength="1"
											autocomplete="off"
											placeholder="请输入字符（A-Z）"
											v-model={data.inputChar}
											class="el-input__inner"
											onInput={e =>{
												// let value = e.target.value;
												// if(value){
												// 	value = value.toLocaleUpperCase();
												// 	this.$set(this.formData,"inputChar",value);
												// 	// this.formData.inputChar = value;
												// 	e.target.inputChar = value;
												// }
												// if(/[a-z]/.test(value)){
												// 	value = value.toLocaleUpperCase();
												// 	this.formData.inputChar = value;
												// 	e.target.inputChar = value;
												// }
												// if(!/[A-Z]/.test(value)){
												// 	this.$nextTick(() =>{
												// 		this.$set(this.formData,"inputChar","");
												// 		e.target.inputChar = '';
												// 	});

												// 	return;
												// };
											}}
										/>
									</div>
								</div>
							</el-col>
						</el-row>
					</div>,
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					showCancelButton: true,
					closeOnClickModal: false,
					beforeClose: (action, instance, done) => {
						if (action === 'confirm') {
							if(String(data.inputNumber).length == 1){
								data.inputNumber = "0" + String(data.inputNumber);
							}
							if(!/[A-Z]/.test(data.inputChar)){
								this.$notify.warning({title: '提示信息',message:'只可输入【A-Z】!'});
								return false;
							}
							instance.confirmButtonLoading = true;
							instance.confirmButtonText = '执行中...';
							done();
							instance.confirmButtonLoading = false;
							instance.confirmButtonText = '确定';
						} else {
							done();
						}
					}
				}).then(({value}) => {
					// console.log("then.data.inputNumber => ",data.inputNumber)
					//生成账号
					this.loadingVm = this.openLoding('.cover-container');
					//调用提交
					//不再使用由IMG转FILE
					// data = this.transformAllEnclosure(data);
					data.auditStatus = types.DEALER_INFO_STATUS_TO_BE_SUBMITTED;
					this.saveDetermine(data);
				}).catch(() => {
				});
			},
			// infoOpinionChange(data){
				// this.saveDetermine();
			// },
			//转化表单的附件 转换为list<Map<String,Object>>（提交前使用）
			//不再使用由IMG转FILE
			transformAllEnclosure(data){
				let rdata = Object.assign({},data);

				rdata.designFeeEnclosureList = this.transformEnclosureList(rdata.designFeeEnclosureList);	//设计费附件
				rdata.cashDepositEnclosureList = this.transformEnclosureList(rdata.cashDepositEnclosureList);	//保证金附件

				rdata.businessLicenseEnclosureList = this.transformEnclosureList(rdata.businessLicenseEnclosureList);	//营业执照扫描件
				rdata.legalRepresentativeEnclosureList = this.transformEnclosureList(rdata.legalRepresentativeEnclosureList);	//法定代表人附件
				rdata.firstPaymentEnclosureList = this.transformEnclosureList(rdata.firstPaymentEnclosureList);	//首笔提车款附件

				rdata.openAccountProveEnclosureList = this.transformEnclosureList(rdata.openAccountProveEnclosureList);	//开户证明附件

				rdata.licenceEnclosureList = this.transformEnclosureList(rdata.licenceEnclosureList);	//许可证附件
				return rdata;
			},
			//转化表单的附件 转换为list<Sting>（回显使用）
			transformAllEnclosureString(data){
				let rdata = data;

				rdata.designFeeEnclosureList = this.transformEnclosureStringList(rdata.designFeeEnclosureList);	//设计费附件
				rdata.cashDepositEnclosureList = this.transformEnclosureStringList(rdata.cashDepositEnclosureList);	//保证金附件

				rdata.businessLicenseEnclosureList = this.transformEnclosureStringList(rdata.businessLicenseEnclosureList);	//营业执照扫描件
				rdata.legalRepresentativeEnclosureList = this.transformEnclosureStringList(rdata.legalRepresentativeEnclosureList);	//法定代表人附件
				rdata.firstPaymentEnclosureList = this.transformEnclosureStringList(rdata.firstPaymentEnclosureList);	//首笔提车款附件

				rdata.openAccountProveEnclosureList = this.transformEnclosureStringList(rdata.openAccountProveEnclosureList);	//开户证明附件

				rdata.licenceEnclosureList = this.transformEnclosureStringList(rdata.licenceEnclosureList);	//许可证附件

				//经销商形式
				let dealerAttachAuthList = [];
				if(isArray(rdata.dealerAttachAuthList)){
					rdata.dealerAttachAuthList.forEach(x => {
						dealerAttachAuthList.push(x.financeCompanyId);
					});
				}
				rdata.dealerAttachAuthList = dealerAttachAuthList;

				//车系
				let dealerAttachSeriesList = [];
				if(isArray(rdata.dealerAttachSeriesList)){
					rdata.dealerAttachSeriesList.forEach(x => {
						dealerAttachSeriesList.push(x.seriesId);
					});
				}
				rdata.dealerAttachSeriesList = dealerAttachSeriesList;

				//车型
				let dealerAttachModelList = [];
				if(isArray(rdata.dealerAttachModelList)){
					rdata.dealerAttachModelList.forEach(x => {
						dealerAttachModelList.push(x.modelId);
					});
				}
				rdata.dealerAttachModelList = dealerAttachModelList;
				return rdata;
			},
			//转换成附件对象 转换为list<Map<String,Object>>
			transformEnclosureList(list){
				let fileUrlList = [];
				if(!isArray(list)){
					return fileUrlList;
				}
				//不再使用由IMG转FILE
				// for (let i = 0; i < list.length; i++) {
				// 	let fileUrl = list[i];
				// 	fileUrl = fileUrl.replace(/\\/g,"/");
				// 	fileUrlList.push(Object.assign({},{"name":fileUrl.substring(fileUrl.lastIndexOf('/')+1)},{"url":fileUrl}));
				// }
				// return fileUrlList;
				return list;
			},
			//转换成附件对象(回显) 转换为list<Sting>
			transformEnclosureStringList(list){
				let fileUrlList = [];
				if(!isArray(list)){
					return fileUrlList;
				}
				//不再使用由IMG转FILE
				// for (let i = 0; i < list.length; i++) {
				// 	let fileUrl = list[i];
				// 	fileUrlList.push(fileUrl.fileId);
				// }
				list.forEach(x => {
					fileUrlList.push({name:x.fileName,url:x.fileId});
				});
				return fileUrlList;
			},

			async save(data){
				//保存主表数据
				let res = {};
				if(this.value.type === 'add'){
					// res = await addAllData(data);
          res = await addAllData4Serv(data);
				}else{
					res = await editAllData4Serv(this.value.id,data);
				}
				if(res.resultCode === 200) {
					this.$notify.success({title: '提示信息',message:'保存成功!'});
					this.$emit('close','refresh');
				}else {
					this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
				}
			},
			async saveDetermine(data){
				let res = {};
				// console.log("data =>",data);
				// this.closeLoding(this.loadingVm);
				// return;
				if(this.value.type === 'add'){
					res = await addDetermine(data);
				}else{
					res = await editDetermine(this.value.id,data);
				}
				if(res.resultCode === 200) {
					this.$notify.success({title: '提示信息',message:'确认成功!'});
					this.$emit('close','refresh');
				}else {
					this.$notify.error({title: '提示信息',message:res.errMsg||'确认失败!'});
				}
			},
		},
	};
</script>

<style scoped>
	.wrapper,.line {
		height: calc(100vh - 135px);
	}
	.line{
		overflow-x:hidden;
		overflow-y:auto;
	}
</style>
